let app = getApp()
const host = app.host;
let setToken = function (token) {
    const res = tt.setStorageSync("token", token);
}

let getToken = function () {
    return tt.getStorageSync("token");
}

let setAccessToken = function (token) {
    const res = tt.setStorageSync("access_token", token);
}

let getAccessToken = function () {
    return tt.getStorageSync("access_token");
}
let reportAnalytics = function(eventName, data) {
     tt.reportAnalytics(eventName, data);
}

let promisify = function (func, options = {}) {
    return new Promise((resolve, reject) => {
        func({
            ...options,
            success(res) {
                resolve(res);
            },
            fail(err) {
                reject(err);
            },
        });
    });
}
let checkText = async function (content) { //图片检测
    let options = {
        url: "https://developer.toutiao.com/api/v2/tags/text/antidirt",
        data: {
            "tasks": [{
                "content": content
            }]
        },
        header: {
            "content-type": "application/json",
            "X-Token": getAccessToken(),
        },
        method: "POST",
        dataType: "json", // 指定返回数据的类型为 json
        responseType: "text"
    }
    let res = await promisify(tt.request, options);
    const predicts = res.data.data?.[0]?.predicts?.[0]?.hit;
    if (!predicts) {
        return true;
    } else {
        tt.showToast({
            icon: "fail",
            title: "输入文字违规"
        });
        return false;
    }
}
async function login(shareUserId) {
    let microLoginRes = await promisify(tt.login);
    let option = {
        url: `${host}/user/login`,
        data: {
        code: microLoginRes.code,
        anonymousCode: microLoginRes.anonymousCode,
        type: app.type,
        shareUserId
        },
        method: "POST"
    }
    let loginRes = await promisify(tt.request, option);
    let loginData = loginRes.data;
    let token = null;
    if (loginData.status === 0) {
        token = loginData.object;
        setToken(token);
    } else {
        console.log(loginRes);
    }
}

let requestAccessToken = async function() {
    const options = {
      url:  `${host}/api/getToken`, //请求地址
      method: "GET",
      header: {
        'token': getToken()
      },   
      dataType: "json",
      timeout:50000, //超时时间，单位为毫秒（最大值 50000ms)
    }
    let task = tt.request({
      ...options,
      success(res) { //请求成功回调199199
        setAccessToken(res.data.object)
      },
      fail(res) {//请求失败回调
        console.log("请求失败", res.errMsg);
        tt.showToast({
          title: "请求失败",
          icon: "none"
        });
      },
    });
}
const sysInfo = tt.getSystemInfoSync();
let isIOS = sysInfo.platform == 'ios'
let chooseLocalImge = async function() {
    let chooseImage = null;
    try {
        let sourceType = ['album']
        if (!isIOS) {
        sourceType.push('camera')
        } 
        let options = {
        sourceType,
        sizeType: ['original', 'compressed']
        }
        chooseImage = await promisify(tt.chooseImage, options)
    } catch (error) {
        throw  '请先开启访问相册的权限，选择带有人像的图片'
    } 

    let filePath = chooseImage.tempFilePaths[0]
    return filePath;
} 
let chooseMultiLocalImge = async function() {
    let chooseImage = null;
    try {
        let sourceType = ['album']
        if (!isIOS) {
        sourceType.push('camera')
        } 
        let options = {
        sourceType,
        sizeType: ['original', 'compressed']
        }
        chooseImage = await promisify(tt.chooseImage, options)
    } catch (error) {
        throw  '请先开启访问相册的权限，选择带有人像的图片'
    } 

    let filePathList = chooseImage.tempFilePaths
    return filePathList;
}

let showLoading = function(mes) {
    if (!mes) {
        mes = "处理中..."
    }
    tt.showLoading({
        title: mes,
        icon: 'none',
        success: (res) => {
            console.log(res);
        },
        fail: (res) => {   
            console.log(res);
        },
    });
}

let hideLoading = function() {
    tt.hideLoading({
        success: (res) => {
            console.log(res);
        },
        fail: (res) => {
            console.log(res);
        },
    });
}
let savePic = function(filePath){
    tt.saveImageToPhotosAlbum({
        filePath: filePath,
        success: (res) => {
          tt.showToast({
            title: "保存成功"
          });
        },
        fail: (res) => {
            console.log(res);
          tt.showToast({
            title: "保存失败"
          });
        },
      });
}
let downloadFile = async function(url) {
    let res = await promisify(tt.downloadFile, {url})
    return res.tempFilePath;
}
let removeTempFile = async function() {
    let fileListResult;
    try {
        fileListResult = await promisify(tt.getSavedFileList)
    } catch (e) {
        console.log(e);
        return;
    }
    
    console.log(fileListResult);
    for (let file of fileListResult.fileList) {
        let filePath = file.filePath;
        let removeResult = await promisify(tt.removeSavedFile, {filePath})
    }
}
let showErrorMessage = function(msg) {
    tt.showToast({
        title: msg,
        icon: "fail",
        success: (res) => { },
        fail: (res) => {},
    });
}
let showNoneMessage = function(msg) {
    tt.showToast({
        title: msg,
        icon: "none",
        success: (res) => { },
        fail: (res) => {},
    });
}
let showSuccessMessage = function(msg) {
    tt.showToast({
        title: msg,
        icon: "success",
        success: (res) => { },
        fail: (res) => {}
        })
}
let setTitle = function(title) {
    tt.setNavigationBarTitle({
        title,
        success: (res) => {
          
        },
        fail: (res) => {
          
        },
      });
}
let back = function() {
    tt.navigateBack({
        success: (res) => {
          
        },
        fail: (res) => {
          
        },
      });
}
let navigate = function(url) {
    tt.navigateTo({
        url,
        success: (res) => {
            console.log(res);
        },
        fail: (res) => {
            console.log(res);
        },
    });
}
let copyText = function(text) {
    tt.setClipboardData({
        data: text,
        success: (res) => {
            showSuccessMessage('复制成功')
        },
        fail: (res) => {}
    })
}

export {
    setToken,
    getToken,
    setTitle,
    promisify,
    setAccessToken,
    getAccessToken,
    checkText,
    requestAccessToken,
    login,
    chooseLocalImge,
    chooseMultiLocalImge,
    showLoading,
    hideLoading,
    savePic,
    downloadFile,
    removeTempFile,
    showErrorMessage,
    showSuccessMessage,
    showNoneMessage,
    back,
    navigate,
    copyText, 
    reportAnalytics
}